package com.jokul.controller;

import java.io.*;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.jokul.model.Account;
import com.jokul.service.UserService;
/**
 * 用户登录
 * @author jokul
 *
 */
@WebServlet(name = "Login", urlPatterns = "/login.do", initParams = {
		@WebInitParam(name = "SUCCESS", value = "member.jsp"),
		@WebInitParam(name = "ERROR", value = "index.jsp") })
public class Login extends HttpServlet {

	private static final long serialVersionUID = 1L;
	private String SUCCESS_VIEW;
	private String ERROR_VIEW;

	private UserService userService;

	public void init() throws ServletException {
		SUCCESS_VIEW = getInitParameter("SUCCESS");
		ERROR_VIEW = getInitParameter("ERROR");
		userService = (UserService) getServletContext().getAttribute(
				"userService");
	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
		Account account = new Account();
		account.setName(username);
		account.setPassword(password);

		String page = ERROR_VIEW;
		request.setAttribute("username", username);
		boolean b = userService.isUserExisted(account);
		if (b) {
			HttpSession session = request.getSession();
			session.setAttribute("login", username);
			page = SUCCESS_VIEW;
			request.getRequestDispatcher(page).forward(request, response);
		} else {
			response.sendRedirect(page);
		}
	}
}
